package com.springapp.security;

import com.springapp.model.User;
import com.springapp.repository.UserRepository;
import com.springapp.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created with IntelliJ IDEA. User: kataeva.nat
 */
public class Interceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;
    @Autowired
    private UserRepository userRepository;
    private final Logger log = LoggerFactory.getLogger(Interceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest,
            HttpServletResponse httpServletResponse, Object o) throws Exception {
        if (httpServletRequest.getPathInfo().equals("/login")) {
            String login = httpServletRequest.getParameter("login");
            String password = httpServletRequest.getParameter("password");
            User user = userRepository.findByLoginAndPassword(login, password);
            if (user != null) {
                httpServletResponse.addHeader("name", user.getName());
                httpServletResponse.addHeader("login", user.getLogin());
                httpServletResponse.addHeader("key", KeyGenerator.generateUUID());
                httpServletResponse.addHeader("id", user.getId().toString());
                return false;
            }
        } else {
            String key = httpServletRequest.getHeader("key");
            if (userRepository.findByKey(key) != null) {
                return true;
            } else {
                httpServletResponse.sendRedirect("/login");
                return false;
            }
        }
        log.info("pre-handle");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
            HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        //To change body of implemented methods use File | Settings | File Templates.
        log.info("post-handle");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
            HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        log.info("after-handle");
    }
}
